<template>
  <div class="trackOut">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <p>{{ $t("TrackOut") }}</p>
      </div>
      <p class="lot-Information">{{ this.$t('lotInformation') }}</p>
      <el-form
        :model="formInline"
        class="form-inline"
        label-width="140px"
      >
        <el-form-item :label="$t('handlerId')">
          <el-input v-model="$route.params.eqp1Id" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('testerId')">
          <el-input v-model="formInline.eqp2ID" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('lotId')">
          <el-input v-model="formInline.lotId" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('processFlow')">
          <el-input v-model="formInline.processFlow" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('productName')">
          <el-input v-model="formInline.productName" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('packageType')">
          <el-input v-model="formInline.packageType" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('testProgramName')">
          <el-input v-model="formInline.trProgram" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('customerLotId')">
          <el-input v-model="formInline.custLotID" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('customer')">
          <el-input v-model="formInline.custName" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('workOrder')">
          <el-input v-model="formInline.workOrder" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('remark')">
          <el-input v-model="formInline.Remark" />
        </el-form-item>
        <el-form-item v-if="formInline.finishHold" :label="$t('holdCode')">
          <el-input v-model="formInline.finishHoldCode" @keydown.enter.native="checkHoldCode"/>
        </el-form-item>
        <el-form-item v-if="formInline.finishHold" :label="$t('holdMsg')">
          <el-input v-model="formInline.holdMsg" :disabled="true"/>
        </el-form-item>
        <!-- v-if="formInline.lossFlag" -->
        <el-form-item v-if="lossFlag" :label="$t('lossReason')">
          <el-select v-model="formInline.lossReason" >
            <el-option
              v-for="item in lossFlagList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        v-if="formInline.mesTrackOut"
        :model="formInline"
        class="form-inline"
        label-width="140px"
      >
        <el-col :span="6">
          <el-form-item :label="$t('interrupt')">
            <el-switch
              v-model="formInline.lotEnd"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Run Hold">
            <el-switch
              v-model="formInline.runHold"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Finish Hold">
            <el-switch
              v-model="formInline.finishHold"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="clearDate"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="type"
          label="#"
          width="90"/>
        <el-table-column
          :label="$t('testedQty')">
          <template slot-scope="scope">
            <template v-if="scope.row.type == $t('testMachineData')">
              <el-input v-model="tableData[0]['testedQty']" :disabled="true" />
            </template>
            <template v-if="scope.row.type == $t('actualData')">
              <el-input v-model="tableData[1]['testedQty']" onkeyup="this.value = this.value.replace(/[^\d]/g,'')"/>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('passQty')"
          prop="passQty">
          <template slot-scope="scope">
            <template v-if="scope.row.type == $t('testMachineData')">
              <el-input v-model="tableData[0]['passQty']" :disabled="true" />
            </template>
            <template v-if="scope.row.type == $t('actualData')">
              <el-input v-model="tableData[1]['passQty']" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" @blur="computerNum"/>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="Yield"
          width="90">
          <template slot-scope="scope">
            <template v-if="scope.row.type == $t('testMachineData')">
              <el-input v-model="tableData[0]['yield']" :disabled="true" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" />
            </template>
            <template v-if="scope.row.type == $t('actualData')">
              <el-input v-model="tableData[1]['yield']" :disabled="true" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" />
            </template>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item,index) in tableColumn"
          :key="index"
          :prop="item.prop"
          :label="item.label">
          <template slot-scope="scope">
            <template v-if="scope.row.type == $t('testMachineData')">
              <el-input v-model="tableData[0]['binQty'+`${index+1}`]" :disabled="true" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" />
            </template>
            <template v-if="scope.row.type == $t('actualData')">
              <el-input v-model="tableData[1]['binQty'+`${index+1}`]" onkeyup="this.value = this.value.replace(/[^\d]/g,'')" @input="changeInput(item)"/>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="trackOut-btns">
        <el-col :span="6">
          <!-- v-btnPermission:cancel -->
          <el-button
            v-btnPermission:cancel
            :loading="cancelTrackInLoading"
            :disabled="cancelTrackInDisable"
            type="primary"

            icon="el-icon-document-delete"
            @click="cancelTrackIn"
          >
            {{ $t('cancelPitstop') }}
          </el-button>
        </el-col>
        <el-col :span="2" :offset="12">
          <el-button
            :loading="btnLoading"
            :disabled="btnDisable"
            type="primary"

            icon="el-icon-receiving"
            @click="approval">
            {{ $t("TrackOut") }}
          </el-button>
        </el-col>
      </div>
    </el-card>
  </div>
</template>
<script>
import trackApi from '@/api/production/track'
import { selectitemlist } from '@/api/system/attributes'
import mySetting from '@/mixins/mySetting'
import networkTips from '@/mixins/networkTips'
import { replaceStr } from '@/utils/notification'
export default {
  name: 'TrackOut',
  components: {},
  mixins: [mySetting, networkTips],
  data() {
    return {
      btnLoading: false,
      cancelTrackInLoading: false,
      cancelTrackInDisable: false,
      formInline: {},
      tableColumn: [],
      tableData: [{ type: this.$t('testMachineData') }, { type: this.$t('actualData') }],
      lossFlagList: [],
      btnDisable: false,
      lossFlag: false
    }
  },
  created() {
    this.getTrackOutInfo()
    this.getlossFlagList()
  },
  mounted() {},
  methods: {
    // 获取trackout工单信息
    async getTrackOutInfo() {
      const res = await trackApi.getTrackOutInfo({ eqp1Id: this.$route.params.eqp1Id })
      if (res.code === 1) {
        this.formInline = res.data
        this.formInline.sysTestInfo.binQtyList.map((ele) => {
          this.tableColumn.push({
            prop: 'binQty' + ele.binNo,
            label: 'bin' + ele.binNo
          })
          this.tableData[0][`binQty${ele.binNo}`] = ele.binQty
          this.$set(this.tableData[1], `binQty${ele.binNo}`, ele.binQty)
        })
        const { testedQty, passQty } = res.data.sysTestInfo
        this.$set(this.tableData[1], 'testedQty', testedQty)
        this.$set(this.tableData[1], 'passQty', passQty)
        // yield关键字不能用 保险点
        this.$set(this.tableData[1], 'yield', res.data.sysTestInfo.yield)
        this.tableData[0].testedQty = testedQty
        this.tableData[0].passQty = passQty
        this.tableData[0].yield = res.data.sysTestInfo.yield
      }
    },
    // 确认结批接口
    trackOutCommit() {
      this.computerNum() && this.checkIsNull() && this.trackOutProcess()
    },
    // 确认开批
    approval() {
      this.$confirm(this.$t('sureTrackOut'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.trackOutCommit()
      })
    },
    // 开批接口流程
    trackOutProcess() {
      this.btnLoading = true
      const arr = Object.keys(this.tableData[1]).filter(item => {
        if (/binQty/g.test(item)) return item
      }).map((ele, index) => {
        return {
          binNo: index + 1,
          binQty: this.tableData[1][ele] || 0
        }
      })
      this.formInline.physicalInfo.binQtyList = arr || []
      this.formInline.physicalInfo.testedQty = this.tableData[1]['testedQty']
      this.formInline.physicalInfo.passQty = this.tableData[1]['passQty']
      // yield前端 不算,后端算
      this.formInline.physicalInfo.yield = 0
      // delete this.formInline.sysTestInfo
      trackApi.trackOutCommit(this.$clearNull(this.formInline)).then((res) => {
        if (res.code === 1) {
          this.btnDisable = true
          this.btnLoading = false
          this.$notify({
            title: this.$t('1'),
            type: 'success',
            message: replaceStr(this.$t(String(res.message)), Array.isArray(res.data) ? res.data : [res.data]),
            duration: 0
          })
        } else {
          this.$alert(replaceStr(this.$t(String(res.message)), res.data), this.$t('trackOutErrorInfo'), {
            confirmButtonText: this.$t('determine'),
            type: 'warning',
            callback: action => {
              this.btnLoading = false
            }
          })
        }
      }).catch((rej) => {
        this.btnLoading = false
        this.$notify.error({
          title: this.$t('0'),
          duration: 0
        })
      })
    },
    // 取消开批
    cancelTrackIn() {
      this.cancelTrackInLoading = true
      const tempObj = {
        eqp1Id: this.formInline.eqp1ID,
        eqp2Id: this.formInline.eqp2ID,
        lotId: this.formInline.lotId
      }
      trackApi.cancelTrackIn(tempObj).then(res => {
        if (res.code === 1) {
          this.cancelTrackInLoading = false
          this.cancelTrackInDisable = true
        } else {
          this.cancelTrackInDisable = false
          this.cancelTrackInLoading = false
        }
        this.$betterTips(res)
      })
    },
    async checkHoldCode() {
      const res = await trackApi.checkHoldCode({ holdCode: this.formInline.finishHoldCode })
      if (res.code === 1) {
        this.btnDisable = false
        this.netTips(res)
      } else {
        this.btnDisable = true
        this.netTips(res)
      }
      this.$set(this.formInline, 'holdMsg', res.data.holdMsg)
    },
    async getlossFlagList() {
      const res = await selectitemlist({ name: 'LOSS_REASON' })
      this.lossFlagList = res.data
    },
    computerNum() {
      if (parseInt(this.tableData[1].testedQty) < parseInt(this.tableData[1].passQty)) {
        this.$notify({
          type: 'warning',
          title: this.$t('testNumberNotLessGoodProducts'),
          duration: 0
        })
        return false
      }
      const num = ((this.tableData[1].passQty / this.tableData[1].testedQty) * 100).toFixed(2) + '%'
      this.$set(this.tableData[1], 'yield', num)
      return true
    },
    clearDate() {
      this.$set(this.formInline, 'holdCode', '')
      this.$set(this.formInline, 'holdMsg', '')
    },
    changeInput(row) {
      if (parseInt(row.label.replace(/[^0-9]/ig, '')) === parseInt(this.formInline.lossBinNo)) {
        const prop = row.prop
        if (Number(this.tableData[1][prop]) > 0) {
          this.lossFlag = true
        } else {
          this.lossFlag = false
          this.$set(this.formInline, 'lossReason', '')
        }
      }
    },
    // 提交前的验证
    checkIsNull() {
      const temp = ['testedQty', 'passQty']
      const isNull = temp.filter(input => {
        return this.tableData[1][input] === ''
      })
      if (isNull.length) {
        const listVNode = isNull.map(node => {
          return (
            <p>
              <span>{`请填写:${this.$t(node)}`}</span>
            </p>
          )
        })
        this.$notify({
          message: this.$createElement('div', { style: 'color: teal' }, listVNode),
          type: 'error',
          duration: 0
        })
        return false
        // return true语义化
      } else {
        return true
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.box-card {
  width: 1100px;
  margin: 20px auto;
  p {
    font-size: 16px;
    font-weight: bold;
  }
  .lot-Information{
    margin-top: 0;
  }
}
::v-deep .el-card__header {
  padding: 0;
  padding-left: 15px;
}
.el-form{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
.el-form-item {
  width: 48%;
  margin-bottom: 20px;
  .el-select {
    width: 100%;
  }
}
}
.el-row {
  margin-top: 20px;
}
::v-deep.el-table .cell{
  padding:0 4px;
}
.trackOut-btns{
  width: 100%;
  padding: 20px 0;
  display: flex;
  justify-content: space-between;
}
</style>
